package com.example.gkcircle.fragment.love;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.example.gkcircle.App;
import com.example.gkcircle.BaseFragment;
import com.example.gkcircle.MainActivity;
import com.example.gkcircle.R;
import com.example.gkcircle.activity.MovieCommentActivity;
import com.example.gkcircle.adapter.MovieAdapter;
import com.example.gkcircle.bean.Movie;
import com.example.gkcircle.override.RecylerViewOnScrollListener;
import com.example.gkcircle.utils.DateUtil;
import com.example.gkcircle.utils.PicUtil;
import com.example.gkcircle.utils.ToastFactory;

import java.util.ArrayList;
import java.util.List;


/**
 * 约电影
 * @author ZhouHua
 * created at 15/12/21 上午12:54
 */
public class MovieFragment extends BaseFragment implements CompoundButton.OnCheckedChangeListener{


    private RecyclerView mGirlRecyclerView;
    private RecyclerView mBoyRecyclerView;
    private MovieAdapter mGirlAdapter;
    private MovieAdapter mBoyAdapter;
    private SwipeRefreshLayout mSwipe;
    private RadioButton mGirlRadioBtn;
    private RadioButton mBoyRadioBtn;
    private LinearLayout mHeaderLayout;

    private MovieAdapter.SpaceItemDecoration spaceItemDecoration;
    //判断是否为女生列或者男生
    private boolean isBoyFlag;//默认为女生列
    //当前加载页
    private int girlCurrentPage = 0;
    private int boyCurrentPage=0;
    //最加加载数
    private final int maxDataCount = 10;
    //正在刷新
    private boolean girlIsRefreshing;
    private boolean boyIsRefreshing;
    //暂无加载
    private boolean noMoreGirlData;
    private boolean noMoreboyData;

    private static MovieFragment instance;
    public static MovieFragment getInstance() {
        if (instance == null) instance = new MovieFragment();
        return instance;
    }

    @Override
    protected int setLayout() {
        return R.layout.love_movie_fragment;
    }

    @Override
    protected void initView(View view) {
        this.mSwipe=(SwipeRefreshLayout)view.findViewById(R.id.love_movie_swipe);
        this.mGirlRecyclerView=(RecyclerView)view.findViewById(R.id.love_movie_girl_recyclerview);
        this.mBoyRecyclerView=(RecyclerView)view.findViewById(R.id.love_movie_boy_recyclerview);
        this.mGirlRadioBtn=(RadioButton)view.findViewById(R.id.love_movie_girl_radio_btn);
        this.mBoyRadioBtn=(RadioButton)view.findViewById(R.id.love_movie_boy_radio_btn);
        this.mHeaderLayout=(LinearLayout)view.findViewById(R.id.love_movie_header);
        this.mGirlRadioBtn.setTextColor(getResources().getColor(R.color.white));
        this.mBoyRadioBtn.setTextColor(getResources().getColor(R.color.boy));
        mSwipe.setColorSchemeColors(getResources().getColor(R.color.main), getResources().getColor(R.color.love), getResources().getColor(R.color.wish));
        //瀑布流布局
        StaggeredGridLayoutManager sglm1=new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        StaggeredGridLayoutManager sglm2=new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        mGirlRecyclerView.setLayoutManager(sglm1);
        mBoyRecyclerView.setLayoutManager(sglm2);
        if(null==spaceItemDecoration){
            spaceItemDecoration=new MovieAdapter.SpaceItemDecoration(20,15,15,15);
            mGirlRecyclerView.addItemDecoration(spaceItemDecoration);
            mGirlRecyclerView.setItemAnimator(new DefaultItemAnimator());
            mBoyRecyclerView.addItemDecoration(spaceItemDecoration);
            mBoyRecyclerView.setItemAnimator(new DefaultItemAnimator());
        }
    }

    private void displayMenu(int firstVisiableItem){
        if (MainActivity.mFloatingActionButton != null) {
            if (MainActivity.firstVisiableItem > firstVisiableItem) {
                MainActivity.firstVisiableItem = firstVisiableItem;
            }

            if (MainActivity.firstVisiableItem == firstVisiableItem) {
                MainActivity.mFloatingActionButton.setVisibility(View.VISIBLE);
                MainActivity.mTabbar.setVisibility(View.VISIBLE);
                mHeaderLayout.setVisibility(View.VISIBLE);
            } else if((isBoyFlag && null!=mBoyAdapter && mBoyAdapter.getItemCount()>=5) || (!isBoyFlag && null!=mGirlAdapter && mGirlAdapter.getItemCount()>=5)) {
                MainActivity.mFloatingActionButton.setVisibility(View.GONE);
                MainActivity.mTabbar.setVisibility(View.GONE);
                mHeaderLayout.setVisibility(View.GONE);
                MainActivity.firstVisiableItem = firstVisiableItem - 1;
                if (MainActivity.mFloatingActionMenu.isOpen()) {
                    MainActivity.mFloatingActionMenu.close(true);
                }
            }
        }
    }
    @Override
    protected void initListener() {
        mGirlRadioBtn.setOnCheckedChangeListener(this);
        mBoyRadioBtn.setOnCheckedChangeListener(this);

        mGirlRecyclerView.setOnScrollListener(new RecylerViewOnScrollListener() {
            //加载更多
            @Override
            public void onBottom() {
                super.onBottom();
                if(noMoreboyData)return;
                if(!isBoyFlag)if(noMoreGirlData)return;
                else if(noMoreboyData)return;
                girlCurrentPage++;
                loadMoreData();
            }

            //隐藏和显示浮动菜单
            @Override
            public void firstVisiableItem(int firstVisiableItem) {
                super.firstVisiableItem(firstVisiableItem);
                displayMenu(firstVisiableItem);
            }
        });

        mBoyRecyclerView.setOnScrollListener(new RecylerViewOnScrollListener() {
            //加载更多
            @Override
            public void onBottom() {
                super.onBottom();
                if(noMoreboyData)return;
                if(!isBoyFlag)if(noMoreGirlData)return;
                else if(noMoreboyData)return;
                boyCurrentPage++;
                loadMoreData();
            }

            //隐藏和显示浮动菜单
            @Override
            public void firstVisiableItem(int firstVisiableItem) {
                super.firstVisiableItem(firstVisiableItem);
                displayMenu(firstVisiableItem);
            }
        });

        //下拉刷新
        mSwipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (!isBoyFlag) {
                    if (girlIsRefreshing) return;
                    girlCurrentPage = 0;
                    girlIsRefreshing = true;
                    noMoreGirlData = false;
                } else {
                    if (boyIsRefreshing) return;
                    boyCurrentPage = 0;
                    boyIsRefreshing = true;
                    noMoreboyData = false;
                }
                refreshData();
            }
        });


    }

    //刷新数据
    private void refreshData(){
        getData(0, new IGetDataListener() {
            @Override
            public void complete(List<AVObject> list) {
                if(!isBoyFlag){
                    if (App.mMovieGirlList == null)App.mMovieGirlList = new ArrayList<Movie>();
                    App.mMovieGirlList.clear();

                }else{
                    if (App.mMovieBoyList == null)App.mMovieBoyList = new ArrayList<Movie>();
                    App.mMovieBoyList.clear();
                }
                for (int i = 0; i < list.size(); i++) {
                    Movie movie = new Movie();
                    Log.i("test", "complete: " + list.get(i).get("content"));
                    movie.setUser(list.get(i).getAVUser("user"));
                    movie.setObjectId(list.get(i).getObjectId());
                    movie.setContent(list.get(i).get("content").toString());
                    movie.setCreatedAt(DateUtil.getLastMinTime(list.get(i).getDate("createdAt").getTime()));
                    movie.setTags(list.get(i).getList("tags"));
                    movie.setSex(list.get(i).getBoolean("sex"));
                    movie.setCommentCount(list.get(i).getAVObject("commentCount").getInt("likeCount"));
                    movie.setCommentCountObjectId(list.get(i).getAVObject("commentCount").getObjectId());
                    movie.setViewCount(list.get(i).getAVObject("like").getInt("likeCount"));
                    movie.setViewCountObjectId(list.get(i).getAVObject("like").getObjectId());
                    AVFile avFile=list.get(i).getAVFile("photo");
                    if(null!=avFile){
                        if(null!=avFile.getMetaData("width") && null!=avFile.getMetaData("height")){
                            movie.setPhotoWidth(Integer.parseInt(avFile.getMetaData("width").toString()));
                            movie.setPhotoHeight(Integer.parseInt(avFile.getMetaData("height").toString()));
                        }
                        int width= (App.screenWidth- PicUtil.dip2px(getActivity(), 20))/2;
                        movie.setThumbnailUrl(avFile.getThumbnailUrl(true, width, width));
                        movie.setPhotoUrl(avFile.getUrl());
                    }
                    if(!isBoyFlag)App.mMovieGirlList.add(movie);
                    else App.mMovieBoyList.add(movie);
                }
                mSwipe.setRefreshing(false);
                if(!isBoyFlag){
                    girlIsRefreshing=false;
                    if(mGirlAdapter!=null){
                        mGirlAdapter.notifyDataSetChanged();
                        return;
                    }
                    mGirlAdapter = new MovieAdapter(getActivity(), App.mMovieGirlList);
                    mGirlRecyclerView.setAdapter(mGirlAdapter);
                    mGirlAdapter.setOnItemClickListener(new MovieAdapter.OnRecyclerViewItemClickListener() {
                        @Override
                        public void onItemClick(View view, int position) {
                            Intent intent=new Intent(getActivity(), MovieCommentActivity.class);
                            Bundle bundle=new Bundle();
                            bundle.putInt("position",position);
                            bundle.putBoolean("sex",false);
                            intent.putExtras(bundle);
                            startActivity(intent);
                        }
                    });
                }else{
                    boyIsRefreshing=false;
                    if(mBoyAdapter!=null){
                        mBoyAdapter.notifyDataSetChanged();
                        return;
                    }
                    mBoyAdapter = new MovieAdapter(getActivity(), App.mMovieBoyList);
                    mBoyRecyclerView.setAdapter(mBoyAdapter);
                    mBoyAdapter.setOnItemClickListener(new MovieAdapter.OnRecyclerViewItemClickListener() {
                        @Override
                        public void onItemClick(View view, int position) {
                            Intent intent=new Intent(getActivity(), MovieCommentActivity.class);
                            Bundle bundle=new Bundle();
                            bundle.putInt("position",position);
                            bundle.putBoolean("sex",true);
                            intent.putExtras(bundle);
                            startActivity(intent);
                        }
                    });
                }
            }
        });
    }

    //加载更多数据
    private void loadMoreData(){
        getData(!isBoyFlag ? girlCurrentPage : boyCurrentPage, new IGetDataListener() {
            @Override
            public void complete(List<AVObject> list) {
                for (int i = 0; i < list.size(); i++) {
                    Movie movie = new Movie();
                    movie.setUser(list.get(i).getAVUser("user"));
                    movie.setObjectId(list.get(i).getObjectId());
                    movie.setContent(list.get(i).get("content").toString());
                    movie.setCreatedAt(DateUtil.getLastMinTime(list.get(i).getDate("createdAt").getTime()));
                    movie.setTags(list.get(i).getList("tags"));
                    movie.setSex(list.get(i).getBoolean("sex"));
                    movie.setViewCount(list.get(i).getAVObject("like").getInt("likeCount"));
                    movie.setCommentCount(list.get(i).getAVObject("commentCount").getInt("likeCount"));
                    movie.setCommentCountObjectId(list.get(i).getAVObject("commentCount").getObjectId());
                    movie.setViewCountObjectId(list.get(i).getAVObject("like").getObjectId());
                    AVFile avFile=list.get(i).getAVFile("photo");
                    if(null!=avFile){
                        movie.setPhotoWidth(Integer.parseInt(avFile.getMetaData("width").toString()));
                        movie.setPhotoHeight(Integer.parseInt(avFile.getMetaData("height").toString()));
                        int width= (App.screenWidth- PicUtil.dip2px(getActivity(), 20))/2;
                        movie.setThumbnailUrl(avFile.getThumbnailUrl(true,width,width));
                        movie.setPhotoUrl(avFile.getUrl());
                    }
                    if (!isBoyFlag) App.mMovieGirlList.add(movie);
                    else App.mMovieBoyList.add(movie);
                }
                mSwipe.setRefreshing(false);
                if (!isBoyFlag) {
                    mGirlAdapter.notifyDataSetChanged();
                } else {
                    mBoyAdapter.notifyDataSetChanged();
                }
            }
        });
    }


    @Override
    protected void setData() {
        setRadioBtnStyle();
        mSwipe.setRefreshing(true);
        if(!isBoyFlag){
            if(null!=App.mMovieGirlList && mGirlAdapter != null){
                mSwipe.setRefreshing(false);
                girlIsRefreshing = false;
                mGirlAdapter.notifyDataSetChanged();
                return;
            }
        }else{
            if(null!=App.mMovieBoyList && mBoyAdapter!=null){
                mSwipe.setRefreshing(false);
                boyIsRefreshing = false;
                mBoyAdapter.notifyDataSetChanged();
                return;
            }
        }
        refreshData();
    }


    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()){
            case R.id.love_movie_girl_radio_btn:
                if (!isChecked) {mGirlRadioBtn.setTextColor(getResources().getColor(R.color.love)); mGirlRecyclerView.setVisibility(View.GONE);return;}
                isBoyFlag=false;
                mGirlRadioBtn.setTextColor(getResources().getColor(R.color.white));
                mBoyRadioBtn.setTextColor(getResources().getColor(R.color.boy));
                //显示女生数据
                mGirlRecyclerView.setVisibility(View.VISIBLE);
                setData();
                break;
            case R.id.love_movie_boy_radio_btn:
                if(!isChecked){mBoyRadioBtn.setTextColor(getResources().getColor(R.color.boy));mBoyRecyclerView.setVisibility(View.GONE);return;}
                isBoyFlag=true;
                mBoyRadioBtn.setTextColor(getResources().getColor(R.color.white));
                mGirlRadioBtn.setTextColor(getResources().getColor(R.color.love));
                //显示男生数据
                mBoyRecyclerView.setVisibility(View.VISIBLE);
                setData();
                break;
        }
    }
    private void setRadioBtnStyle(){
        if(!isBoyFlag){
            mGirlRadioBtn.setTextColor(getResources().getColor(R.color.white));
            mBoyRadioBtn.setTextColor(getResources().getColor(R.color.boy));
        }else{
            mBoyRadioBtn.setTextColor(getResources().getColor(R.color.white));
            mGirlRadioBtn.setTextColor(getResources().getColor(R.color.love));
        }
    }


    //获取数据
    public IGetDataListener getDataListener;

    private interface IGetDataListener {
        void complete(List<AVObject> list);
    }

    private void getData(int currentPage, final IGetDataListener getDataListener) {
        this.getDataListener = getDataListener;
        AVQuery<AVObject> query = new AVQuery<>("Movie");
        query.setCachePolicy(AVQuery.CachePolicy.NETWORK_ELSE_CACHE);
        query.setLimit(maxDataCount);
        query.setSkip(maxDataCount * currentPage);
        query.orderByDescending("createdAt");
        query.whereEqualTo("sex", isBoyFlag);
        query.include("user");
        query.include("like");
        query.include("commentCount");
        query.findInBackground(new FindCallback<AVObject>() {
            @Override
            public void done(List<AVObject> list, AVException e) {
                if (null==e) {
                    if (list.size() > 0) {
                        if (dataFlag) getDataListener.complete(list);
                        else return;
                    } else {
                        if (dataFlag) {
                            mSwipe.setRefreshing(false);
                            if (!isBoyFlag)noMoreGirlData = true;
                            else noMoreboyData = true;
                            getDataListener.complete(list);
                            ToastFactory.getToast(getActivity(), getResources().getString(R.string.no_more_data)).show();
                        }
                        else return;
                    }
                } else {
                    mSwipe.setRefreshing(false);
                    ToastFactory.getToast(getActivity(), getResources().getString(R.string.connection_error)).show();
                }
            }
        });
    }

}
